<template>
  <div
    class="container flex flex-col min-h-screen bg-primary"
    style="display: block"
  >
    <div class="header bg-primary shadow-lg sticky top-0 z-10 pr-40 pl-40">
      <div
        class="nav flex flex-col sm:flex-row items-center gap-4 text-white py-6"
      >
        <div class="flex items-center gap-3">
          <i class="fa-solid fa-sun text-2xl"></i>
          <p class="text-2xl">新中地天气</p>
        </div>
        <div class="flex gap-4 items-center">
          <h4 class="text-lg">{{ result.city }}</h4>
          <span class="text-sm"
            >实时天气：{{ result.weather }} {{ result.temperature }}℃</span
          >
          <span class="text-sm"
            >{{ result.winddirection }}风{{ result.windpower }}级</span
          >
        </div>
        <div class="flex gap-3 flex-1 justify-end">
          <i
            class="fa-solid fa-circle-info text-xl hover:text-secondary cursor-pointer duration-1000"
            @click="showInfoClick()"
          ></i>
          <i
            class="fa-solid fa-plus text-xl hover:text-secondary duration-150 cursor-pointer"
            style="display: none"
          ></i>
        </div>
      </div>
    </div>
    <div class="content text-white pr-40 pl-40">
      <div class="pt-4 mb-8 relative">
        <input
          type="text"
          placeholder="请输入城市名称"
          class="py-2 px-1 w-full bg-transparent border-b focus:border-weather-secondary focus:outline-none focus:shadow-md"
          v-model="cityselect"
          @input="searchCity()"
        />
        <ul
          class="absolute bg-secondary text-white w-full shadow-md py-2 px-1 top-[62px]"
          v-show="citylist"
          :style="{ display: citylist ? '' : 'none' }"
        >
          <!-- <p style="display: none">对不起网络似乎除了点问题 请稍后再查询</p>
          <p style="display: none">似乎没有找到你查找的城市</p> -->
          <li
            v-for="item in citylist"
            :key="item.adcode"
            class="cursor-pointer py-2"
            @click="handleCitySelect(item.adcode)"
          >
            {{ item.city }}
          </li>
        </ul>
      </div>
      <div
        class="mt-10 max-h-[300px]"
        :style="{ display: lists.length ? '' : 'none' }"
      >
        <div
          class="flex justify-between"
          @mouseover="showButtom = true"
          @mouseleave="showButtom = false"
          v-for="list in lists"
          :key="list.adcode"
        >
          <div
            class="mb-4 bg-secondary py-2 px-4 flex justify-between cursor-pointer w-full duration-300"
            :class="{ 'w-4/5': showButtom }"
          >
            <h3>{{ list.city }}</h3>
            <span>{{list.temp}}度</span>
            
          </div>

          <div
            class="flex mb-4 gap-2"
            v-show="showButtom"
            :style="{ display: showButtom ? '' : 'none' }"
          >
            <button
              class="bg-yellow-500 text-center w-[80px]"
              @click="handleCitySelect(list.adcode)"
            >
              查看
            </button>
            <button
              class="bg-yellow-500 text-center w-[80px]"
              @click="handleDelete(list.adcode)"
            >
              删除
            </button>
          </div>
        </div>
      </div>
      <h2 class="text-center duration-200" v-show="!lists.length">
        暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
      </h2>
      <h2 class="mt-6">近期天气</h2>
      <div class="bg-secondary px-12 pt-10 mt-2 rounded">
        <div class="list flex gap-6">
          <div
            class="flex flex-col flex-1 text-center gap-4"
            v-for="(item, index) in resultall"
            :key="index"
          >
            <span>{{ item.day }}</span>
            <span>{{ item.date.slice(5, 10) }}</span>
            <span>{{ item.dayweather }}</span>
            <span>风力 {{ item.daypower }}级</span>
          </div>
        </div>
        <div class="echart">
          <div ref="chartRef" style="width: 100%; height: 200px"></div>
        </div>
      </div>
    </div>

    <div
      class="fixed z-20 w-full bg-opacity-30 bg-black h-screen top-0 left-0 flex justify-center px-8"
      :class="{ hidden: !showInfo }"
    >
      <div class="p-4 bg-white self-start mt-32 max-w-screen-md">
        <h2>关于:</h2>
        <p class="text-xs mb-4">这个应用可以用来追踪你选择城市的当前天气</p>
        <h2>如何使用:</h2>
        <p class="text-xs mb-4">
          1.点击搜索框输入你希望追踪的城市<br />
          2.在搜索结果中选中一个城市，你将获取当地最新的天气<br />
          3.点击右侧的＋号可以将追踪城市的天气情况保存在首页
        </p>
        <h2>移除城市:</h2>
        <p class="text-xs">
          如果你不想在首页关注某个城市,可以通过底部的按钮删<br />除它
        </p>
        <button
          class="text-white mt-8 bg-primary py-2 px-6 text-xs"
          @click="toggleInfo()"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useCounterStore } from '../stores/counter.js'

const { increment } = useCounterStore()
const router = useRouter()
const chartRef = ref(null) // 创建一个ref来引用图表容器
const showInfo = ref(false)
const showButtom = ref(false)
const result = ref('')
const resultall = ref([])
const result1 = ref('')
const option = ref('')
const day = []
const night = []
const cityselect = ref('')
const timeout = ref(null)
const citylist = ref(null)
const nowday = ref('')
const currentDate = ref('')
const tomorrowday = ref('')
const week = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
const lists = ref([])

// 点击搜索框获取城市列表
function searchCity() {
  clearTimeout(timeout.value)
  timeout.value = setTimeout(async () => {
    if (cityselect.value !== '') {
      const res = await axios.get(
        `https://restapi.amap.com/v3/geocode/geo?address=${cityselect.value}&key=513d613dba4b77bf8089ab3e2822b6c2`
      )
      citylist.value = res.data.geocodes
      // console.log(citylist.value, '1111')
      return
    }
    citylist.value = null
  }, 300)
}

// 点击城市列表跳转路由
function handleCitySelect(adcode) {
  // console.log(adcode)
  router.push({ path: '/about' })
  //传递参数
  increment(adcode)
}
//点击按钮删除本地存储的城市列表
function handleDelete(adcode) {
  const index = lists.value.findIndex((item) => item.adcode === adcode)
  if (index !== -1) {
    lists.value.splice(index, 1)
    localStorage.setItem('savecity', JSON.stringify(lists.value))
  }
}

// 模态框的显示隐藏切换
function toggleInfo() {
  showInfo.value = !showInfo.value
}
// 模态框的点击事件
function showInfoClick() {
  toggleInfo()
}
//发送axios请求获取天气数据
async function getWeatherData() {
  const response = await axios.get(
    'https://restapi.amap.com/v3/ip?key=513d613dba4b77bf8089ab3e2822b6c2'
  )
  // console.log(response)
  result1.value = response.data
  // console.log(result1.value,'result1')

  const response3 = await axios.get(
    `https://restapi.amap.com/v3/weather/weatherInfo?city=${result1.value.adcode}&key=513d613dba4b77bf8089ab3e2822b6c2&extensions=base`
  )
  // console.log(response3)
  result.value = response3.data.lives[0]
  // console.log(result.value, 'result')
  const response4 = await axios.get(
    `https://restapi.amap.com/v3/weather/weatherInfo?city=${result1.value.adcode}&key=513d613dba4b77bf8089ab3e2822b6c2&extensions=all`
  )
  // console.log(response4, 'response4')
  //将数组中数字转换为星期
  resultall.value = response4.data.forecasts[0].casts
  resultall.value.map((item) => {
    nowday.value = week[new Date().getDay()]
    // console.log(nowday.value, 'nowday')
    currentDate.value = new Date()
    tomorrowday.value =
      week[new Date(currentDate.value.getTime() + 24 * 60 * 60 * 1000).getDay()]
    // console.log(tomorrowday.value, 'tomorrowday')
    item.day = week[new Date(item.date).getDay()]
    if (item.day === nowday.value) {
      item.day = '今天'
    } else if (item.day === tomorrowday.value) {
      item.day = '明天'
    }
  })
  // console.log(resultall.value, 'all')

  //筛选出白天和夜晚的气温数据
  day.value = resultall.value.map((item) => +item.daytemp)
  // console.log(day.value)
  night.value = resultall.value.map((item) => +item.nighttemp)
  // console.log(night.value)
  renderChart()
}
//渲染图表
function renderChart() {
  let chart = echarts.init(chartRef.value) // 初始化echarts图表
  option.value = {
    grid: {
      top: '30%',
      left: 0,
      right: 0,
      bottom: 0,
    },
    xAxis: {
      type: 'category',
      show: false,
    },
    yAxis: {
      type: 'value',
      show: false,
    },
    series: [
      {
        type: 'line',
        data: day.value,
        label: {
          show: true,
          position: 'top',
          color: 'white',
          //格式化标签显示内容
          formatter: function (params) {
            return '白' + params.value + '°C'
          },
        },
      },
      {
        type: 'line',
        data: night.value,
        label: {
          show: true,
          position: 'bottom',
          color: 'white',
          formatter: function (params) {
            return '晚' + params.value + '°C'
          },
        },
      },
    ],
  }
  chart.setOption(option.value) // 设置图表配置
}

onMounted(() => {
  getWeatherData() // 获取天气数据
  //拿到本地存储的城市列表
  lists.value = JSON.parse(localStorage.getItem('savecity')) || []
  console.log(lists.value,'lists')
})
</script>

<style scoped></style>
